﻿<%@ Page Title="POS" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="SapPOS.aspx.cs" Inherits="SapB1WebPOS.SapPOS" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!DOCTYPE html>
    <%--<script src="Scripts/barcode/jquery.scannerdetection.js" type="text/javascript"></script>
    <script src="Scripts/barcode/jquery.scannerdetection.compatibility.js" type="text/javascript"></script>--%>
    <script src="Scripts/hotkey/pos-hotkey.js" type="text/javascript"></script>
    <style type="text/css">
        #grid .k-grid-content table tr td, .k-grid-content-locked table tr td
        {
            font-weight: bolder;
            font-size: 12pt;
            font-family: Courier New;
        }
        #girdPayment .k-grid-content table tr td, .k-grid-content-locked table tr td
        {
            color: Red;
            font-weight: bold;
            font-size: 10pt;
            font-family: Courier New;
        }
        .style1
        {
            font-weight: bold;
        }
    </style>
    <script type="text/javascript">
//        removedefaulthelp();
//        function removedefaulthelp() {
//            window.onhelp = function () {
//                return false;
//            }
//        }
//        keydown event handler
//        document.addEventListener('keydown', function (e) {
//            if (e.keyCode == 13 || e.keyCode == 70) { // F or Enter key
//                //toggleFullScreen();
//            }
//            if (e.keyCode == 112) { // F or Enter key
//                alert("AAA");
//                //removedefaulthelp();
//                e.preventDefault();
//                return;
//            }
//        }, false);
       
//        $(document).scannerDetection({
//            endChar: [13], // be sure the scan is complete if key 13 (enter) is detected
//            avgTimeByChar: 40, // it's not a barcode if a character takes longer than 40ms
//            onError: function (barCode) {
//                
//            },
//            onComplete: function (barcode, qty) {
//                setTimeout(function () { $("#Barcode").focus(); }, 1);
//                $("#Barcode").val(barCode);
//                var e = $.Event("keydown");
//                e.keyCode = 13; // # Some key code value
//                $('#Barcode').trigger(e);
//            } // main callback function
//        });

    </script>
    <script type="text/javascript">
        var docDatePicker, taxDateDatePicker;
        var oItem = {};
        var oWarehouse = {};
        var oVatGroup = {};
        var oDocLine = {};
        var oDocHeader = {};
        var isInsert = "1";
        var gird;
        var girdPayment;
        var docEntry = 0;
        var isUpdate = false;
        var docStatus;
        var editRowIndex = -1;
        var docTotal = 0;
        var totalPaymentAmount = 0;
        var currentPage = "SapPOS.aspx";
       
        function PrintReceipt() {
            var docEntry = $("#DocEntry").val();
            if (docEntry != '' && docEntry!='0') {
                $.ajax({
                    type: "POST",
                    url: currentPage + "/PrintReceipt",
                    data: JSON.stringify({
                        docEntry: docEntry
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var html = data.d;
                        var popupWindow = window.open('', 'Print', 'left=1,top=1,scrollbars=1,width=730,height=450,toolbar=1,menubar=1');
                        popupWindow.document.write(html);
                        popupWindow.document.close();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (jqXHR.status == 500) {
                            alert('Internal error: ' + jqXHR.responseText);
                        } else {
                            alert('Unexpected error.' + jqXHR.responseText);
                        }
                    }
                });
            }
        }
        function AddNewItem() {
            OpenItemList();
        }
        function EditItem() {
            if (editRowIndex >= 0) {
                var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
                var params = "?ItemCode=" + rowData.ItemCode + "&Dscription=" + rowData.Dscription + "&unitMsr=" + rowData.unitMsr + "&Quantity=" + rowData.Quantity + "&PriceBefDi=" + rowData.PriceBefDi + "&DiscPrcnt=" + rowData.DiscPrcnt + "&LineNum=" + rowData.LineNum + "";
                params = params + "&WhsCode=" + rowData.WhsCode + "&VatGroup=" + rowData.VatGroup + "&SlpCode=" + rowData.SlpCode;
                var wnd = $("#editLineItem")
                        .kendoWindow({
                            title: "Edit Item",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 900,
                            height: 400,
                            content: { type: "POST", url: "SAPPOSLineEdit.aspx" + params, data: {} },
                            iframe: true
                        }).data("kendoWindow");
                wnd.center().open();
                wnd.bind('close', function () {
                    setTimeout(function () { $("#Barcode").focus(); }, 1);
                    $("#editLineItem").empty();
                });
            }
            else {
                setMasterMessage("Please select the row you would like to EDIT.", "error");
            }
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }
        function UserUpdateLine(lineNum, itemCode, quantity, price, discount, warehouse, tax, salesPerson, dscription) {
            var vatPrcnt = 0;
            $.each(oVatGroup, function (i, o) {
                if (o.Code == tax) {
                    vatPrcnt = o.Rate;
                }
            });
            $.ajax({
                type: "POST",
                url: currentPage + "/UserUpdateLine",
                data: JSON.stringify({
                    lineNum: lineNum,
                    itemCode: itemCode,
                    quantity: quantity,
                    priceBefDi: price,
                    discount: discount,
                    warehouse: warehouse,
                    taxCode: tax,
                    taxRate: vatPrcnt,
                    salesPerson: salesPerson,
                    dscription: dscription
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    grid.dataSource.read();

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            if ($("#editLineItem").data("kendoWindow") != null) {
                $("#editLineItem").empty();
                $("#editLineItem").data("kendoWindow").close();
            }
        }
        function DeleteItem() {
            if (editRowIndex >= 0) {
                var r = confirm("Do you really want to DELETE this item?");
                if (r == true) {
                    var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
                    var lineNum = rowData.LineNum;
                    $.ajax({
                        type: "GET",
                        url: currentPage + "/DeleteDocLine",
                        data: {
                            lineNum: lineNum
                        },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            grid.dataSource.remove(rowData);
                            UpdateTotal();
                            editRowIndex = -1;
                        },
                        failure: function (response) {
                            alert(response.d);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            if (jqXHR.status == 500) {
                                alert('Internal error: ' + jqXHR.responseText);
                            } else {
                                alert('Unexpected error.' + jqXHR.responseText);
                            }
                        }
                    });
                }
            }
            else {
                setMasterMessage("Please select the row you would like to DELETE.", "error");
            }
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }

        function PaymentOnChange(arg) {
            var selectedRows = this.select();
            var selectedDataItems = [];
            for (var i = 0; i < selectedRows.length; i++) {
                var dataItem = this.dataItem(selectedRows[i]);
                selectedDataItems.push(dataItem);
            }
            if (selectedDataItems.length > 0 && isUpdate == false) {
                var params = "?PaymentCode=" + selectedDataItems[0].PaymentCode + "&GrandTotal=" + docTotal + "&TotalPaymentAmount=" + totalPaymentAmount;
                var wnd = $("#paymentAmount")
                        .kendoWindow({
                            title: "Payment Amount",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 600,
                            height: 270,
                            content: { type: "POST", url: "PaymentAmount.aspx" + params, data: {} },
                            iframe: true
                        }).data("kendoWindow");
                wnd.center().open();
                wnd.bind('close', function () {
                    setTimeout(function () { $("#Barcode").focus(); }, 1);
                    $("#paymentAmount").empty();
                });
            }
        }
        function UpdatePayment(amount, paymentCode) {
            var items = $("#girdPayment").data("kendoGrid").dataSource.data();
            var updateRowIndex = -1;
            var totalGridPaymentAmount = 0;
            var totalAmount = 0;

            for (i = 0; i < items.length; i++) {
                var item = items[i];
                if (isUpdate == false) {
                    if (item.PaymentCode == paymentCode) {
                        item.set("Amount", 0);
                        updateRowIndex = i;
                    }
                }
                totalGridPaymentAmount += item.Amount;
            }

            grandTotal = docTotal;

            totalAmount = parseFloat(amount) + parseFloat(totalGridPaymentAmount);

            if (totalAmount > grandTotal) {
                amount = grandTotal - totalGridPaymentAmount;
            }
            if (updateRowIndex > -1) {
                items[updateRowIndex].set("Amount", amount);

            }
            totalPaymentAmount = parseFloat(amount) + parseFloat(totalGridPaymentAmount)
            $('#totalPaymentAmount').text(format2(totalPaymentAmount, ""));
            if ($("#paymentAmount").data("kendoWindow") != null) {
                $("#paymentAmount").empty();
                $("#paymentAmount").data("kendoWindow").close();
            }
        }
        function CreateNew() {
            $.ajax({
                type: "POST",
                url: currentPage + "/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    setTimeout(function () { $("#Barcode").focus(); }, 1);
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });
            location.href = currentPage + "?DocEntry=0&IsUpdate=false";
        }
        function OpenCustomerList() {
            var wnd = $("#customerList")
                        .kendoWindow({
                            title: "List of Business Partners",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 800,
                            height: 500,
                            content: { type: "POST", url: "BusinessPartnersList.aspx?CardType=C", data: {} },
                            iframe: true
                        }).data("kendoWindow");
            wnd.center().open();
            wnd.bind('close', function () {
                setTimeout(function () { $("#Barcode").focus(); }, 1);
                $("#customerList").empty();
            });
        }
        function OpenItemList() {
            var cardCode = $("#CardCode").val();
            if (cardCode != '') {
                var wnd = $("#itemList")
                        .kendoWindow({
                            title: "List of Item Master Data",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1100,
                            height: 500,
                            content: { type: "POST", url: "ItemMasterDataList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");
                wnd.center().open();
                wnd.bind('close', function () {
                    setTimeout(function () { $("#Barcode").focus(); }, 1);
                    $("#itemList").empty();
                });
            }
        }
        function OpenARList() {
            var wnd = $("#salesQuotationList")
                        .kendoWindow({
                            title: "List of A/R Invoice",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1200,
                            height: 500,
                            content: { type: "POST", url: "ARInvoiceList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
            wnd.bind('close', function () {
                setTimeout(function () { $("#Barcode").focus(); }, 1);
                $("#salesQuotationList").empty();
            });
        }
        function setEnabledAddNewItemButton(enabled) {
            if (enabled) {
                $(".k-add-button").removeClass("k-state-disabled").addClass("k-grid-add");
            }
            else {
                $(".k-add-button").addClass("k-state-disabled").removeClass("k-grid-add");
            }
        }
        function ChooseCustomer(customerID, customerName) {
            setEnabledAddNewItemButton(true);
            setTimeout(function () { $("#Barcode").focus(); }, 1);
            selectedCustomerID = customerID;
            $("#CardCode").val(customerID)
            $("#CardName").val(customerName)
            if ($("#customerList").data("kendoWindow") != null) {
                $("#customerList").empty();
                $("#customerList").data("kendoWindow").close();
            }

        }
        function LoadDefaultBP() {
            $.ajax({
                type: "POST",
                url: currentPage + "/GetDefaultBP",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.length > 0) {
                            $("#CardName").val(result[0].CardName);
                            $("#CardCode").val(result[0].CardCode);
                            setEnabledAddNewItemButton(true);
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }
        function LoadBP() {
            var cardCode = $("#CardCode").val();
            $.ajax({
                type: "POST",
                url: currentPage + "/GetBPByCardCode",
                data: JSON.stringify({
                    cardCode: cardCode
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.length > 0) {
                            $("#CardName").val(result[0].CardName)
                            setEnabledAddNewItemButton(true);
                        }
                        else {
                            ajaxindicatorstop();
                            OpenCustomerList();
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }
        function ChooseAR(header) {
            $.ajax({
                type: "POST",
                url: currentPage + "/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    grid.dataSource.data([]);
                    LoadHeader(header);
                    docEntry = header.DocEntry;
                    grid.dataSource.read();
                    girdPayment.dataSource.read();
                    isUpdate = true;
                    var url = currentPage + "?DocEntry=" + docEntry + "&IsUpdate=true"
                    history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            $("#salesQuotationList").data("kendoWindow").close();
            $("#salesQuotationList").empty();
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }


        function lineTotalTextBox(container, options) {
            $('<span name ="LineTotal" id ="LineTotal"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function priceAftetDiscountTextBox(container, options) {
            $('<span name ="Price" id ="Price"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function totalTextBox(container, options) {
            $('<span name ="Total" id ="Total"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function priceBeforeDiscountTextBox(container, options) {
            $('<span name ="TotalBefDisc" id ="TotalBefDisc"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function uoMTextBox(container, options) {
            $('<span name ="unitMsr" id ="unitMsr"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function warehousekendoComboBox(container, options) {
            $('<input    data-text-field="WhsName" data-value-field="WhsCode" Name="WhsCode" ID="WhsCode" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            filter: "contains",
                            placeholder: "[Select Warehouse]",
                            suggest: true,
                            dataSource: oWarehouse
                        });
        }
        function vatkendoComboBox(container, options) {
            $('<input   data-text-field="Name" data-value-field="Code" Name="VatGroup" ID="VatGroup" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            filter: "contains",
                            placeholder: "[Select VAT]",
                            suggest: true,
                            dataSource: oVatGroup,
                            change: function (e) {
                                var cmb = this;
                                if (cmb.selectedIndex < 0) {
                                    cmb.value(null);
                                }
                                else {
                                    var changedCode = this.value();
                                    var vatPrcnt = 0;
                                    $.each(oVatGroup, function (i, o) {
                                        if (o.Code == changedCode) {
                                            vatPrcnt = o.Rate;
                                        }
                                    });
                                    var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
                                    rowData.set('VatPrcnt', vatPrcnt)
                                    UpdateRow(rowData);
                                    UpdateTotal();
                                }
                            }
                        });
        }
        function itemTextBox(container, options) {
            $('<input  disabled style="width:80%;" name="ItemCode" id="ItemCode" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px; cursor: pointer;" onclick="OpenItemList()"  title="Choose item" ></span>').appendTo(container);
        }
        function itemkendoComboBox(container, options) {
            $('<input disabled style="width:90%;" name="Dscription" id="Dscription" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;cursor: pointer;" onclick="OpenItemList()"  title="Choose item" ></span>').appendTo(container);
        }
        function ChooseItem(itemCode, itemName, basePrice, uom, vatGourpSa, vatGourpPu, whsCode) {
            var cardCode = $("#CardCode").val();
            var docDate = $("#docDate").val();
            $.ajax({
                type: "POST",
                url: currentPage + "/GetDataBySelectedItemCode",
                data: JSON.stringify({
                    itemCode: itemCode,
                    cardCode: cardCode,
                    refDate: docDate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result) {
                            grid.dataSource.read();
                            UpdateTotal();
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });

            setTimeout(function () { $("#Barcode").focus(); }, 1);

            if ($("#itemList").data("kendoWindow") != null) {
                $("#itemList").data("kendoWindow").close();
                $("#itemList").empty();
            }
        }
        function UpdateRow(rowData) {
            var discountAmt = 0;
            var priceAfterDiscount = 0;
            var totalAfterDiscount = 0;
            var vatSum = 0;
            var totalBeforeDiscount = 0;
            var vatPrcnt = 0, discount = 0, unitPrice = 0, quantity = 0, total = 0;

            vatPrcnt = rowData.VatPrcnt;
            discount = rowData.DiscPrcnt;
            unitPrice = rowData.PriceBefDi;
            quantity = rowData.Quantity;

            priceAfterDiscount = unitPrice * (100 - discount) / 100;
            totalBeforeDiscount = unitPrice * quantity;
            totalAfterDiscount = priceAfterDiscount * quantity;

            vatSum = (totalAfterDiscount * vatPrcnt) / 100;
            total = totalAfterDiscount + vatSum;

            rowData.set('Price', priceAfterDiscount);
            rowData.set('VatSum', vatSum);
            rowData.set('LineTotal', totalAfterDiscount);
            rowData.set('TotalBefDisc', totalBeforeDiscount);
            rowData.set('Total', total);
        }
        function GetWarehouses() {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetWareHouses",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oWarehouse = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }

        function GetTaxs() {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetTaxs",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oVatGroup = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetItemMasterDataByItemCode(itemCode) {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetItemMasterDataByItemCode",
                data: JSON.stringify({
                    itemCode: itemCode
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result) {
                            var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
                            rowData.set('ItemCode', result[0].ItemCode);
                            rowData.set('Dscription', result[0].ItemName)
                            rowData.set('PriceBefDi', result[0].Price);
                            rowData.set('unitMsr', result[0].InvntryUom);
                            rowData.set('VatGroup', result[0].VatGourpSa);
                            var vatPrcnt = 0;
                            var vatGroupName;
                            $.each(oVatGroup, function (i, o) {
                                if (o.Code == result[0].VatGourpSa) {
                                    vatPrcnt = o.Rate;
                                    vatGroupName = o.Name;
                                }
                            });
                            rowData.set('VatGroupName', vatGroupName);
                            rowData.set('VatPrcnt', vatPrcnt)
                            if ($('#VatGroup').data("kendoDropDownList") != null) {
                                $('#VatGroup').data("kendoDropDownList").value(result[0].VatGourpSa);
                            }
                            if ($('#WhsCode').data("kendoDropDownList") != null) {
                                $('#WhsCode').data("kendoDropDownList").select(0);
                            }
                            UpdateRow(rowData);
                            UpdateTotal();
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function POSChooseItem(itemCode, itemName) {
            if ($("#itemList").data("kendoWindow") != null) {
                $("#itemList").data("kendoWindow").close();
                $("#itemList").empty();
            }
            var cardCode = $("#CardCode").val();
            var docDate = $("#docDate").val();
            $.ajax({
                type: "POST",
                url: currentPage + "/GetDataBySelectedItemCode",
                data: JSON.stringify({
                    itemCode: itemCode,
                    cardCode: cardCode,
                    refDate: docDate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result) {
                            if (result.length == 1) {
                                grid.dataSource.read();
                                UpdateTotal();

                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }
        function GetDataByBarcode(barcode) {
            var cardCode = $("#CardCode").val();
            var docDate = $("#docDate").val();
            $.ajax({
                type: "POST",
                url: currentPage + "/GetDataByBarcode",
                data: JSON.stringify({
                    barcode: barcode,
                    cardCode: cardCode,
                    refDate: docDate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {

                        var result = JSON.parse(response.d);
                        if (result) {
                            if (result == "-1") {
                                setMasterMessage("No data found. ", "error");
                            }
                            else if (result != "2" && result != "4") { // 1 line
                                if (result[0].ObjType == "2") { // Customer
                                    $("#CardCode").val(result[0].ObjCode);
                                    $("#CardName").val(result[0].ObjName);
                                    setEnabledAddNewItemButton(true);
                                }
                                else {
                                    if (cardCode != '') {
                                        // Item
                                        grid.dataSource.read();
                                        UpdateTotal();
                                    } else {
                                        setMasterMessage("Please input Customer.", "error");
                                        return;
                                    }
                                }
                            }
                            else { // >2 line
                                if (result == "2") { // Customer
                                    var wnd = $("#customerList")
                                    .kendoWindow({
                                        title: "List of Business Partners",
                                        modal: true,
                                        visible: false,
                                        resizable: false,
                                        width: 800,
                                        height: 500,
                                        content: { type: "POST", url: "POSBusinessPartnersList.aspx", data: {} },
                                        iframe: true
                                    }).data("kendoWindow");
                                    wnd.center().open();
                                    wnd.bind('close', function () {
                                        $("#customerList").empty();
                                        setTimeout(function () { $("#Barcode").focus(); }, 1);
                                    });
                                }
                                else {
                                    var wnd = $("#itemList")
                                    .kendoWindow({
                                        title: "List of Item Master Data",
                                        modal: true,
                                        visible: false,
                                        resizable: false,
                                        width: 1100,
                                        height: 500,
                                        content: { type: "POST", url: "POSItemMasterDataList.aspx", data: {} },
                                        iframe: true
                                    }).data("kendoWindow");
                                    wnd.center().open();
                                    wnd.bind('close', function () {
                                        $("#itemList").empty();
                                        setTimeout(function () { $("#Barcode").focus(); }, 1);
                                    });
                                }
                            }
                        }
                    }
                    $("#Barcode").val('');
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            setTimeout(function () { $("#Barcode").focus(); }, 1);
        }
        function resizeGrid() {
            var gridElement = $("#grid"),
        dataArea = gridElement.find(".k-grid-content"),
        gridHeight = gridElement.innerHeight(),
        otherElements = gridElement.children().not(".k-grid-content"),
        otherElementsHeight = 0;
            otherElements.each(function () {
                otherElementsHeight += $(this).outerHeight();
            });
            dataArea.height(gridHeight - otherElementsHeight);
            gridElement.height($(document).height() - 350);
        }
        function resizePaymentGrid() {
            var gridElement = $("#girdPayment"),
        dataArea = gridElement.find(".k-grid-content"),
        gridHeight = gridElement.innerHeight(),
        otherElements = gridElement.children().not(".k-grid-content"),
        otherElementsHeight = 0;
            otherElements.each(function () {
                otherElementsHeight += $(this).outerHeight();
            });
            dataArea.height(gridHeight - otherElementsHeight);
            gridElement.height($(document).height() - 350);
        }

        $(window).resize(function () {
            resizeGrid();
            resizePaymentGrid();
        });
        $(document).ready(function () {


            window.onhelp = function () {
                return false;
            }
            inithotkey();

            setTimeout(function () { $("#Barcode").focus(); }, 1);
            $("#Barcode").keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    var barCode = $("#Barcode").val();
                    barCode = barCode.trim();
                    if (barCode != '') {
                        GetDataByBarcode(barCode);
                        $("#Barcode").val('');
                    }
                    return false;
                }
            });
            LoadDefaultBP();
            docDatePicker = $("#docDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDateTimePicker");
            taxDateDatePicker = $("#taxDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDatePicker");

            $(".k-datepicker").find('span').find('input').attr("readonly", "readonly");
            isUpdate = '<%= Request.QueryString["IsUpdate"] %>';
            if (isUpdate == 'false') {
                isUpdate = false;
            }
            if (isUpdate == 'true') {
                isUpdate = true;
            }
            $('#DocEntry').val('<%= Request.QueryString["DocEntry"] %>');
            docEntry = $('#DocEntry').val();

            GetWarehouses();
            GetTaxs();

            if (docEntry != null && docEntry != '0') {
                GetHeaderByDocEntry();
            }

            //Clear Session
            $.ajax({
                type: "POST",
                url: currentPage + "/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //Load Grid
                    grid = $("#grid").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    type: "GET",
                                    url: currentPage + "/GetDocLines",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) {
                                        if ($('#CardCode').val() != '') {
                                            setEnabledAddNewItemButton(true);
                                        }
                                        else {
                                            setEnabledAddNewItemButton(false);
                                        }
                                        UpdateTotal();

                                    }
                                },
                                destroy: {
                                    type: "GET",
                                    url: currentPage + "/DeleteDocLine",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) {
                                        UpdateTotal();
                                    }
                                },
                                parameterMap: function (data, operation) {
                                    if (operation === "read") {
                                        return { docEntry: docEntry
                                        };
                                    }
                                    if (operation === "destroy") {
                                        return { lineNum: data.LineNum };
                                    }
                                },
                                serverPaging: true,
                                serverSorting: true,
                                serverFiltering: true
                            },
                            type: "odata", //Important!!!!
                            schema: {
                                data: function (a) {
                                    if (a.d != null) {
                                        var data = a.d.Data;
                                        return data;
                                    }
                                },
                                total: "d.Count",
                                model: {
                                    id: "LineNum",
                                    fields: {
                                        DocEntry: { type: "string" },
                                        LineNum: { type: "string" },
                                        Dscription: { type: "string" },
                                        ItemCode: { type: "string" },
                                        WhsCode: { type: "string" },
                                        WhsName: { type: "string" },
                                        VatGroup: { type: "string" },
                                        VatGroupCode: { type: "string" },
                                        VatGroupName: { type: "string" },
                                        unitMsr: { type: "string" },
                                        Quantity: { type: "number" },
                                        VatPrcnt: { type: "number" },
                                        PriceBefDi: { type: "number" },
                                        Price: { type: "number" },
                                        DiscPrcnt: { type: "number" },
                                        LineTotal: { type: "number" },
                                        LineStatus: { type: "LineStatus" },
                                        DocStatus: { type: "LineStatus" },
                                        TotalBefDisc: { type: "number" },
                                        SlpCode: { type: "string" }
                                    }
                                }
                            }
                        },
                        sortable: true,
                        resizable: true,
                        height: $(document).height() - 350,
                        selectable: "row",
                        toolbar: [
                        { template:
                            '<a class="k-button k-button-icontext k-grid-add" href="\\#" onclick="AddNewItem()"><span class="k-icon k-add"></span>Add (F4) </a>' +
                            '<a class="k-button k-button-icontext k-grid-edit" href="\\#" onclick="EditItem()"><span class="k-icon k-edit"></span>Edit (F5) </a>' +
                            '<a class="k-button k-button-icontext k-grid-delete" href="\\#" onclick="DeleteItem()"><span class="k-icon k-delete"></span>Delete (F7) </a>'
                        }],
                        batch: true,
                        columns: [
                        //                            { command: ["edit", "destroy"], title: "Action", width: "260px" },
                            {field: "DocEntry", title: "DocEntry", width: 100, hidden: true },
                            { field: "LineNum", title: "LineNum", width: 150, hidden: true },
                            { field: "LineStatus", title: "LineNum", width: 150, hidden: true },
                            { field: "VatPrcnt", title: "VatPrcnt", width: 150, hidden: true },
                            { field: "VatSum", title: "VatSum", width: 150, hidden: true },
                            { field: "ItemCode", title: "Item Code", width: 180, editor: itemTextBox },
                            { field: "Dscription", title: "Item Name", width: 300, editor: itemkendoComboBox },
                            { field: "unitMsr", title: "UoM", width: 80, editor: uoMTextBox },
                            { field: "Quantity", title: "Quantity", width: 110, attributes: { style: "text-align:right;"} },
                            { field: "PriceBefDi", title: "Price", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "TotalBefDisc", title: "Total Before Discount", hidden: true, width: 180, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: priceBeforeDiscountTextBox },
                            { field: "DiscPrcnt", title: "Discount (%)", width: 110, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "Price", title: "Price After Discount", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: priceAftetDiscountTextBox, hidden: true },
                            { field: "LineTotal", title: "Total After Discount ", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: lineTotalTextBox, hidden: true },
                            { field: "WhsCode", title: "Warehouse", width: 220, editor: warehousekendoComboBox, template: "#=WhsName#", hidden: true },
                            { field: "VatGroup", title: "VAT", width: 200, editor: vatkendoComboBox, template: "#=VatGroupName#", hidden: true },
                            { field: "Total", title: "Total", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: totalTextBox },
                            { field: "SlpCode", title: "Sales Person",hidden: true },
                            ],
                        editable: false,
                        edit: function (e) {
                            $('[name="DocEntry"]').attr("disabled", true);
                            $('[name="LineNum"]').attr("disabled", true);
                            $('[name="LineTotal"]').attr("disabled", true);
                            if (e.model.isNew()) {
                                isInsert = "1";
                                e.container
                             .find("input[name=DocEntry]") // get the input element for the field
                             .val($("#DocEntry").val()) // set the value
                             .change(); // trigger change in order to notify the model binding
                                e.model.set("Quantity", 1);

                                var rowsCount = grid.dataSource.total();
                                editRowIndex = rowsCount - 1;
                                OpenItemList();
                            }
                            else {
                                isInsert = "2";
                            }
                        },
                        cancel: function (e) {
                            UpdateTotal();
                        },
                        save: function (e) {
                        },
                        dataBound: onDataBound
                    }).data("kendoGrid");

                    //Load Grid Payment
                    girdPayment = $("#girdPayment").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    type: "GET",
                                    url: currentPage + "/GetPaymentType",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) {
                                        UpdateTotal();
                                    }
                                },
                                parameterMap: function (data, operation) {
                                    if (operation === "read") {
                                        return { docEntry: docEntry
                                        };
                                    }
                                },
                                serverPaging: true,
                                serverSorting: true,
                                serverFiltering: true
                            },
                            type: "json",
                            schema: {
                                data: function (response) {
                                    if (response.d != null) {
                                        var data = response.d;
                                        return JSON.parse(data);
                                    }
                                },
                                total: function (response) {
                                    return JSON.parse(response.d).length;
                                },
                                model: {
                                    id: "PaymentType",
                                    fields: {
                                        PaymentType: { type: "string" },
                                        PaymentCode: { type: "string" },
                                        PaymentName: { type: "string" },
                                        Amount: { type: "number" },
                                        AcctCode: { type: "string" }
                                    }
                                }
                            }
                        },
                        change: PaymentOnChange,
                        sortable: true,
                        resizable: true,
                        height: $(document).height() - 350,
                        selectable: "row",
                        toolbar: [{ template:
                            '<a class="k-button" href="\\#" ><img src="images/money3.png" id="screen" title="$" width="16px" height="16px" style="margin-right:3px;"/>Payment </a>' 
                        }],
                        columns: [
                            { field: "PaymentType", title: "Type", width: 80, hidden: true },
                            { field: "PaymentCode", title: "Code", width: 80, hidden: true },
                            { field: "PaymentName", title: "Name", width: "50%" },
                            { field: "Amount", title: "Amount", width: "50%", format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "AcctCode", title: "AcctCode", width: "30%", hidden: true }
                            ]
                    }).data("kendoGrid");

                    $(".k-grid-add").addClass("k-add-button");
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });
        });
        function onDataBound(e) {
            var grid = $("#grid").data("kendoGrid");
            if (editRowIndex >= 0) {
                var rowNumber = editRowIndex + 5;
                setTimeout(function () {
                    grid.select("tr:eq(" + rowNumber + ")");
                }, 1)
            }
            this.content.scrollTop(this.tbody.height())
            $(grid.tbody).on("click", "td", function (e) {
                var row = $(this).closest("tr");
                editRowIndex = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
            });

            var docStatusOfLine = $('#DocStatus').val();
            //Selects all edit buttons
            $("#grid tbody tr .k-grid-edit").each(function () {
                var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
                //Check in the current dataItem if the row is editable
                if (currentDataItem.LineStatus == 'C') {
                    $(this).remove();
                }
            });

            //Selects all delete buttons
            $("#grid tbody tr .k-grid-delete").each(function () {
                var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
                //Check in the current dataItem if the row is deletable
                if (currentDataItem.LineStatus == 'C') {
                    $(this).remove();
                }
            });
            if (docStatusOfLine == 'Closed' || docStatusOfLine == 'Canceled') {
                $("#grid .k-add").parent().hide();
                $("#grid .k-edit").parent().hide();
                $("#grid .k-delete").parent().hide();
            }
            else {
                $("#grid .k-add").parent().show();
                $("#grid .k-edit").parent().show();
                $("#grid .k-delete").parent().show();
            }
            $(grid.tbody).on("blur", "td", function (e) {
                var row = $(this).closest("tr");
                var rowIdx = $("tr", grid.tbody).index(row);
                editRowIndex = rowIdx;
                var colIdx = $("td", row).index(this);
                var colName = $('#grid').find('th').eq(colIdx).text();
                var columnField = $('#grid').find("th").eq(colIdx).attr("data-field");
                var rowData = $('#grid').data().kendoGrid.dataSource.data()[rowIdx];
                if (columnField == 'Quantity' || columnField == 'PriceBefDi' || columnField == 'DiscPrcnt') {
                    UpdateRow(rowData);
                    UpdateTotal();
                }
                else if (columnField == 'ItemCode') {
                    //GetItemMasterDataByItemCode(rowData.ItemCode);
                }
            });

        }
        function UpdateTotal() {
            var items = $("#grid").data("kendoGrid").dataSource.data();
            var subTotal = 0, taxAmount = 0;
            for (i = 0; i < items.length; i++) {
                var item = items[i];
                subTotal += item.LineTotal;
                taxAmount += item.VatSum;
            }
            var totalMoney = format2(subTotal, "");
            var total = subTotal + taxAmount;
            $('#subTotal').text(totalMoney);
            $('#taxAmount').text(format2(taxAmount, ""));
            $('#total').text(format2(total, ""));
            docTotal = total;
            UpdatePayment(total, "CASH");
        }
        function LoadHeader(docHeader) {
            docEntry = docHeader.DocEntry;
            if (docHeader.CANCELED == 'Y') {
                docStatus = "Canceled";
                $('#btnSave').attr('disabled', 'disabled');
                $('#btnSave').addClass("k-button k-state-disabled");
                $("#Barcode").prop("disabled", true).addClass("k-state-disabled");
                removehotkey();
            }
            else if (docHeader.DocStatus == 'O') {
                docStatus = "Open";
                $('#btnSave').removeAttr('disabled');
                $('#btnSave').removeClass("k-state-disabled");
                $("#Barcode").prop("disabled", false).removeClass("k-state-disabled");
                window.onhelp = function () {
                    return false;
                }
                inithotkey();
            }
            else if (docHeader.DocStatus == 'C') {
                docStatus = "Closed";
                $('#btnSave').attr('disabled', 'disabled');
                $('#btnSave').addClass("k-button k-state-disabled");
                $("#Barcode").prop("disabled", true).addClass("k-state-disabled");
                removehotkey();
            }

            $('#DocEntry').val(docEntry);
            $('#DocStatus').val(docStatus);
            $('#DocStatus').val(docStatus);
            $('#CardCode').val(docHeader.CardCode);
            $('#CardName').val(docHeader.CardName);
            var docDate = docHeader.DocDate;
            var docDateobj = kendo.parseDate(docDate);
            var validDate = docHeader.TaxDate;
            var validDateobj = kendo.parseDate(validDate);
            $("#docDate").data("kendoDatePicker").value(null);
            $("#docDate").data("kendoDatePicker").value(docDateobj);
            $("#taxDate").data("kendoDatePicker").value(null);
            $("#taxDate").data("kendoDatePicker").value(validDateobj);
        }
        function GetHeaderByDocEntry() {

            $.ajax({
                type: "POST",
                url: currentPage + "/GetDocHeaderByDocEntry",
                data: JSON.stringify({
                    docEntry: docEntry
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.Table) {
                            var docHeader = result.Table;
                            if (docHeader.length > 0) {
                                docHeader = docHeader[0];
                                LoadHeader(docHeader);
                                $("#subTotal").text(format2(docHeader.SubTotal, ""));
                                $("#taxAmount").text(format2(docHeader.VatSum, ""));
                                $("#total").text(format2(docHeader.DocTotal, ""));
                                docTotal = docHeader.DocTotal;
                                isUpdate = true;
                                setTimeout(function () { $("#Barcode").focus(); }, 1);
                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }

        function GetLastRecord() {

            $.ajax({
                type: "POST",
                url: currentPage + "/GetLastRecord",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.Table) {
                            var docHeader = result.Table;
                            if (docHeader.length > 0) {
                                grid.dataSource.data([]);
                                docHeader = docHeader[0];
                                LoadHeader(docHeader);
                                $("#subTotal").text(format2(docHeader.SubTotal, ""));
                                $("#taxAmount").text(format2(docHeader.VatSum, ""));
                                $("#total").text(format2(docHeader.DocTotal, ""));
                                docTotal = docHeader.DocTotal;
                                isUpdate = true;
                                $.ajax({
                                    type: "POST",
                                    url: currentPage + "/ClearSessionData",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    success: function (response) {
                                        grid.dataSource.read();
                                        girdPayment.dataSource.read();
                                        setTimeout(function () { $("#Barcode").focus(); }, 1);
                                        var url = currentPage + "?DocEntry=" + docEntry + "&IsUpdate=true"
                                        history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);

                                    },
                                    failure: function (response) {
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 500) {
                                            alert('Internal error: ' + jqXHR.responseText);
                                        } else {
                                            alert('Unexpected error.' + jqXHR.responseText);
                                        }
                                    }
                                });
                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function Cancel() {
            var r = confirm("Do you really want to cancel this document?");
            if (r == true) {
                $.ajax({
                    type: "POST",
                    url: currentPage + "/CancelDoc",
                    data: JSON.stringify({
                        docEntry: docEntry
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.d != "0") {
                            if ($.isNumeric(data.d)) {
                                isUpdate = true;
                                $('#DocEntry').val(data.d);
                                docEntry = $('#DocEntry').val();
                                grid.dataSource.data([]);
                                GetHeaderByDocEntry();
                                $.ajax({
                                    type: "POST",
                                    url: currentPage + "/ClearSessionData",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    success: function (response) {
                                        var url = currentPage + "?DocEntry=" + docEntry + "&IsUpdate=true"
                                        history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                                        grid.dataSource.read();
                                        girdPayment.dataSource.read();
                                        setTimeout(function () { $("#Barcode").focus(); }, 1);
                                    },
                                    failure: function (response) {
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 500) {
                                            alert('Internal error: ' + jqXHR.responseText);
                                        } else {
                                            alert('Unexpected error.' + jqXHR.responseText);
                                        }
                                    }
                                });
                                setMasterMessage("Operation complete successful!", "success");
                            }
                            else {
                                setMasterMessage(data.d, "error");
                            }
                        }
                        else {
                            setMasterMessage(data.d, "error");
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (jqXHR.status == 500) {
                            alert('Internal error: ' + jqXHR.responseText);
                        } else {
                            alert('Unexpected error.' + jqXHR.responseText);
                        }
                    }
                });
            }
        }
        function UpdateProcess() {

            docEntry = $("#DocEntry").val();
            oDocHeader.DocEntry = $("#DocEntry").val();
            oDocHeader.CardCode = $('#CardCode').val();
            oDocHeader.CardName = $('#CardName').val();
            oDocHeader.DocDate = $("#docDate").val();
            oDocHeader.TaxDate = $("#taxDate").val()
            oDocHeader.Comments = "Web POS";
            oDocHeader.DocTotal = docTotal;

            if (parseFloat(totalPaymentAmount) != parseFloat(docTotal)) {
                setMasterMessage("Please make sure the Total Payment Amount equal the Grand Total.", "error");
                return;
            }
            if (oDocHeader.CardCode == '') {
                setMasterMessage("Please select customer.", "error");
                return;
            }
            if (oDocHeader.DocDate == '') {
                setMasterMessage("Please select Doc Date .", "error");
                return;
            }

            if (oDocHeader.TaxDate == '') {
                setMasterMessage("Please select Tax Date.", "error");
                return;
            }
            setTimeout(function () { $("#Barcode").focus(); }, 1);
            var paymentData = JSON.stringify($('#girdPayment').data("kendoGrid").dataSource.data());
            $.ajax({
                type: "POST",
                url: currentPage + "/UpdateDocToDB",
                data: JSON.stringify({
                    oDocHeader: JSON.stringify(oDocHeader),
                    isUpdate: isUpdate,
                    docEntry: docEntry,
                    paymentData: paymentData
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d != "0") {
                        if ($.isNumeric(data.d)) {
                            ClearPage();
                            setMasterMessage("Operation complete successful!", "success");
                        }
                        else {
                            setMasterMessage(data.d, "error");
                        }
                    }
                    else {
                        setMasterMessage(data.d, "error");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function ClearPage() {
            $.ajax({
                type: "POST",
                url: currentPage + "/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    docEntry = 0;
                    isUpdate = false;
                    $("#DocEntry").val('0');
                    $("#DocStatus").val('');
                    $("#CardCode").val('');
                    $("#CardName").val('');
                    $("#docDate").data("kendoDatePicker").value(null);
                    $("#docDate").data("kendoDatePicker").value(new Date());
                    $("#taxDate").data("kendoDatePicker").value(null);
                    $("#taxDate").data("kendoDatePicker").value(new Date());
                    $('#btnSave').removeAttr('disabled');
                    $('#btnSave').removeClass("k-state-disabled");
                    $("#Barcode").prop("disabled", false).removeClass("k-state-disabled");
                    LoadDefaultBP();
                    var url = currentPage + "?DocEntry=" + docEntry + "&IsUpdate=false";
                    history.pushState({ docEntry: docEntry, IsUpdate: false }, "Document", url);
                    grid.dataSource.read();
                    girdPayment.dataSource.read();
                    editRowIndex = -1;
                    inithotkey();
                    setTimeout(function () { $("#Barcode").focus(); }, 1);
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });

        }
    </script>
    <table style="width: 100%; border: 1px;">
        <tr>
            <td style="width: 8%;">
                Customer
            </td>
            <td style="width: 25%;">
                <input type="text" class="k-input k-textbox" name="CardCode" id="CardCode" required="required"
                    validationmessage="Pls input Customer Code." style="width: 290px;" onchange="LoadBP()" />
                <span class="k-icon k-i-search" style="margin-left: 0px; width: 16px; cursor: pointer;"
                    onclick="OpenCustomerList()" title="Choose Customer" id="spanChooseCustomer">
                </span>
            </td>
            <td>
                Posting Date
            </td>
            <td style="width: 330px;">
                <input type="text" name="docDate" id="docDate" required="required" validationmessage="Pls input Promotion Code."
                    style="width: 290px;" />
            </td>
            <td style="width: 120px;">
                Document No.
            </td>
            <td>
                <input type="text" class="k-input k-textbox" name="DocEntry" id="DocEntry" readonly
                    disabled style="width: 290px;" />
            </td>
        </tr>
        <tr>
            <td>
                Customer Name
            </td>
            <td>
                <textarea rows="2" name="CardName" id="CardName" class="k-textbox" style="width: 290px;"
                    readonly> </textarea>
            </td>
            <td>
                Document Date
            </td>
            <td>
                <input type="text" name="taxDate" id="taxDate" required="required" validationmessage="Pls input Document Date"
                    style="width: 290px;" />
            </td>
            <td>
                Status
            </td>
            <td>
                <input type="text" class="k-input k-textbox" name="DocStatus" id="DocStatus" style="width: 290px;"
                    readonly />
            </td>
        </tr>
    </table>
    <table style="width: 100%; margin-bottom: 5px; margin-top: 5px;">
        <tr>
            <td style="width: 8%;">
                Barcode
            </td>
            <td>
                <input type="text" name="Barcode" id="Barcode" class="form-control input-lg" style="border-radius: 0px;
                    height: 40px; font-size: 13pt; font-weight: bold; width: 100%;" />
            </td>
        </tr>
    </table>
    <div id="paymentAmount">
    </div>
    <div id="customerList">
    </div>
    <div id="salesQuotationList">
    </div>
    <div id="itemList">
    </div>
    <div id="editLineItem">
    </div>
    <table style="width: 100%; margin-right: 5px;height:100%;" border="0px">
        <tr>
            <td style="width: 70%;">
                <div id="grid" style="width: 100%;">
                </div>
            </td>
            <td style="width: 30%;">
                <div id="girdPayment" style="width: 100%;">
                </div>
            </td>
        </tr>
    </table>
    <br />
    <table border="1" style="width:100%;">
        <tr>
            <td style="width: 79%;">
                <table style="width: 100%; background-color: #283593; color: #fff; border-bottom-color: #fff"
                    border="1">
                    <tr>
                        <td style="width: 200px;" align="right">
                            <div style="margin-right: 5px; font-family: Courier New;">
                                <b>Sub Total</b></div>
                        </td>
                        <td style="width: 200px;" align="right">
                            <div style="margin-right: 5px; font-family: Courier New;">
                                <b>Tax Amount </b>
                            </div>
                        </td>
                        <td style="width: 200px;" align="right">
                            <div style="margin-right: 5px; font-family: Courier New;">
                                <b>Grand Total </b>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <span id="subTotal" style="font-weight: bold; color: #fff; font-size: 17pt; margin-right: 5px;
                                font-family: Courier New;"></span>
                        </td>
                        <td align="right">
                            <span id="taxAmount" style="font-weight: bold; color: #fff; font-size: 17pt; margin-right: 5px;
                                font-family: Courier New;"></span>
                        </td>
                        <td align="right">
                            <span id="total" style="font-weight: bold; color: #fff; font-size: 17pt; margin-right: 5px;
                                font-family: Courier New;"></span>
                        </td>
                    </tr>
                </table>
            </td>
            <td style="width: 30%;">
                <table style="width: 100%; background-color: #283593; color: #fff; border-bottom-color: #fff"
                    border="1">
                    <tr>
                        <td align="right">
                            <div style="margin-right: 5px; font-family: Courier New;">
                                <b>Total Payment Amount</b></div>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <span id="totalPaymentAmount" style="font-weight: bold; color: Red; font-size: 17pt;
                                margin-right: 5px; font-family: Courier New;"></span>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <br />
    <table  style="width:100%;" border="0">
        <tr>
            <td style="width: 80%;">
                <div class="k-edit-buttons k-state-default">
                    <button type="button" id="btnSave" onclick="UpdateProcess();" class="k-button k-button-icontext k-primary"
                        style="width: 170px; height: 50px;">
                        <span class="k-icon k-update"></span>Save (F2)</button>
                    <button type="button" id="btnCreateNew" onclick="ClearPage();" class="k-button k-button-icontext k-primary"
                        style="width: 170px; height: 50px;">
                        <span class="k-icon k-i-plus"></span>Create New (F1)</button>
                    <button type="button" id="btnDocumentList" onclick="OpenARList()" class="k-button k-button-icontext k-primary"
                        style="width: 170px; height: 50px;">
                        <span class="k-icon k-i-hbars"></span>A/R Invoice List</button>
                    <button type="button" id="btnLastRecord" onclick="GetLastRecord()" class="k-button k-button-icontext k-primary"
                        style="width: 170px; height: 50px; display: none;">
                        <span class="k-icon k-i-seek-e"></span>Last Record</button>
                </div>
            </td>
            <td align="right">
                <button type="button" id="btnCopyTo" class="k-button k-button-icontext k-primary"
                    style="width: 170px; height: 50px;" onclick="PrintReceipt()">
                    <img src="images/535129-print_512x512.png" id="screen" title="Print" width="16px"
                        height="16px" alt="Print" />
                    Print (F3)</button>
            </td>
        </tr>
    </table>
</asp:Content>
